#!/user/bin/env python
# -*- coding: utf-8 -*-

import tornado
import tornado.web
try:
    import ujson as json
except:
    import json
from controls import data_manage_user_mysql
from utils import log
from config import etc

class BaseHandler(tornado.web.RequestHandler):
    def get_current_user(self):
        return self.get_secure_cookie("username")

class SigninHandler(BaseHandler):
    def get(self):
        self.render('cms/manage_signin.html')
        return

    def post(self):
        try:
            username = self.get_argument('username')
            password = self.get_argument('password')

            if not (username and password):
                log.i('params fetching error')
                self.redirect("/cms/signin")
                return

            correct_password = data_manage_user_mysql.get_password_by_username(username)

            if correct_password == password.strip(' \t\n\r'):
                self.set_secure_cookie("username", self.get_argument("username"))
                self.redirect("/cms/topic")
            else:
                log.i('password not match')
                self.redirect("/cms/signin")
                return

        except Exception as e:
            log.i(e)
            res = {'ret': 1, 'msg': etc.err_500}
            self.write(json.dumps(res))
            self.finish()
            return

class SignoutHandler(BaseHandler):
    def get(self):
        pass

    def post(self):
        pass

class AuthHandler(BaseHandler):
    def get(self):
        if not self.current_user:
            self.redirect("/cms/signin")
            return
        else:
            self.redirect("/cms/topic")
            return